import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/group_message.dart';
import 'package:vista/shared/models/group_snapshot.dart';
import 'package:vista/shared/models/message_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/circle_gallery.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/services/relation_bond.dart';

/// 消息视图模型
/// 管理消息页面的数据和状态
class MessageViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final RelationBond _relationBond;
  final DialogLens _dialogLens;
  final CircleGallery _circleGallery;

  MessageViewModel(
    this._authFocus,
    this._relationBond,
    this._dialogLens,
    this._circleGallery,
  );

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  List<UserFrame> _friends = [];
  List<UserFrame> get friends => _friends;

  List<ChatSessionItem> _chatSessions = [];
  List<ChatSessionItem> get chatSessions => _chatSessions;

  List<GroupSessionItem> _groupSessions = [];
  List<GroupSessionItem> get groupSessions => _groupSessions;

  bool _isRefreshing = false;

  /// 初始化数据
  Future<void> initialize() async {
    // 防止并发刷新
    if (_isRefreshing) return;

    _isRefreshing = true;
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      if (_currentUser == null) {
        setBusy(false);
        _isRefreshing = false;
        return;
      }

      await _loadFriends();
      await _loadChatSessions();
      await _loadGroupSessions();
    } finally {
      setBusy(false);
      _isRefreshing = false;
    }
  }

  /// 加载朋友列表
  Future<void> _loadFriends() async {
    if (_currentUser == null) return;

    final friendIds = await _relationBond.getFriendsList(_currentUser!.id);
    final allUsers = await _authFocus.getUsers();

    _friends =
        allUsers.where((user) => friendIds.contains(user.id)).take(10).toList();
    notifyListeners();
  }

  /// 加载单聊会话列表
  Future<void> _loadChatSessions() async {
    if (_currentUser == null) return;

    final sessionIds = await _dialogLens.getChatSessions(_currentUser!.id);
    final allUsers = await _authFocus.getUsers();

    _chatSessions = [];
    for (final userId in sessionIds) {
      final user = allUsers.firstWhere(
        (u) => u.id == userId,
        orElse: () => allUsers.first,
      );

      final lastMessage = await _dialogLens.getLastMessage(
        userId1: _currentUser!.id,
        userId2: userId,
      );

      final unreadCount = await _dialogLens.getUnreadCountWithUser(
        userId: _currentUser!.id,
        otherUserId: userId,
      );

      _chatSessions.add(
        ChatSessionItem(
          user: user,
          lastMessage: lastMessage,
          unreadCount: unreadCount,
        ),
      );
    }
    notifyListeners();
  }

  /// 加载群聊会话列表
  Future<void> _loadGroupSessions() async {
    if (_currentUser == null) return;

    final groupIds = await _circleGallery.getUserGroups(_currentUser!.id);
    final allGroups = await _circleGallery.getAllGroups();

    _groupSessions = [];
    for (final groupId in groupIds) {
      final group = allGroups.firstWhere(
        (g) => g.id == groupId,
        orElse: () => allGroups.first,
      );

      final messages = await _circleGallery.getGroupMessages(groupId);
      final lastMessage = messages.isNotEmpty ? messages.last : null;

      _groupSessions.add(
        GroupSessionItem(group: group, lastMessage: lastMessage),
      );
    }

    // 按最后一条消息时间排序
    _groupSessions.sort((a, b) {
      if (a.lastMessage == null && b.lastMessage == null) return 0;
      if (a.lastMessage == null) return 1;
      if (b.lastMessage == null) return -1;
      return b.lastMessage!.timestamp.compareTo(a.lastMessage!.timestamp);
    });

    notifyListeners();
  }

  /// 检查是否有与用户的对话
  Future<bool> hasChatWithUser(String otherUserId) async {
    if (_currentUser == null) return false;

    final messages = await _dialogLens.getChatMessages(
      userId1: _currentUser!.id,
      userId2: otherUserId,
    );

    return messages.isNotEmpty;
  }

  /// 创建对话（发送一条初始消息）
  Future<void> createChatWithUser(String otherUserId) async {
    if (_currentUser == null) return;

    await _dialogLens.sendTextMessage(
      senderId: _currentUser!.id,
      receiverId: otherUserId,
      content: 'Hello!',
    );
  }

  /// 刷新数据
  Future<void> refresh() async {
    await initialize();
  }
}

/// 单聊会话项
class ChatSessionItem {
  final UserFrame user;
  final MessageShot? lastMessage;
  final int unreadCount;

  ChatSessionItem({required this.user, this.lastMessage, this.unreadCount = 0});
}

/// 群聊会话项
class GroupSessionItem {
  final GroupSnapshot group;
  final GroupMessage? lastMessage;

  GroupSessionItem({required this.group, this.lastMessage});
}
